package com.unlcn.ils.crsc.service.sysadmin.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.unlcn.ils.crsc.dao.mapper.sysadmin.UserMapper;
import com.unlcn.ils.crsc.dao.mapper.sysadmin.UserRoleMapper;
import com.unlcn.ils.crsc.dao.model.sysadmin.User;
import com.unlcn.ils.crsc.dao.model.sysadmin.UserRole;
import com.unlcn.ils.crsc.dao.model.sysadmin.bo.UserBo;
import com.unlcn.ils.crsc.service.sysadmin.UserService;
import com.unlcn.ils.crsc.service.util.BaseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;


@Service
public class UserServiceImpl implements UserService {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);


    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public int updateUser(User user) throws Exception {
       return userMapper.updateById(user);
    }

    @Override
    public User addUser(User user) throws Exception {
        int i = userMapper.insert(user);
        if(i>0){
            return user;
        }else{
            throw new BaseException("新增错误");
        }
    }

    @Override
    public int deleteUser(List<Integer> ids) throws Exception {
        return userMapper.deleteBatchIds(ids);
    }

    @Override
    public int assignRole(Integer userId, List<Integer> roleIds) throws Exception {

        if (Objects.equals(userId, null)) {
            LOGGER.error("UserServiceImpl.assignRole param uid must not be null ");
            throw new IllegalArgumentException("用户id不能为空");
        }

        //查询角色数据库中的角色
        EntityWrapper<UserRole> ew = new EntityWrapper<>();
        ew.eq("user_id",userId);
        List<UserRole> dbUserRoles = userRoleMapper.selectList(ew);

        List<Integer> dbRoleIds = new ArrayList<>();
        dbUserRoles.stream().forEach(userRole -> dbRoleIds.add(userRole.getId()));

        authorize(userId,roleIds,dbRoleIds);
        return 1;
    }

    @Override
    public Page<UserBo> queryPageUser(Page<UserBo> page) {
        List<UserBo> userBos = userMapper.queryPageUser(page,buildCondition(page.getCondition()));
        page.setRecords(userBos);
        return page;

    }

    private EntityWrapper<UserBo> buildCondition(Map<String,Object> condition){
        EntityWrapper<UserBo> ew = new EntityWrapper<>();
        if(!Objects.equals(condition,null)) {
            for (Map.Entry<String, Object> entry : condition.entrySet()) {
                if (entry.getKey().equals("code")) {
                    ew.eq("code", entry.getValue().toString());
                }
                if (entry.getKey().equals("name")) {
                    ew.like("name", entry.getValue().toString());
                }
                if (entry.getKey().equals("orgId")) {
                    ew.eq("org_id", entry.getValue().toString());
                }
                if (entry.getKey().equals("mobile")) {
                    ew.like("mobile", entry.getValue().toString());
                }
                if (entry.getKey().equals("tel")) {
                    ew.like("tel", entry.getValue().toString());
                }
                if (entry.getKey().equals("email")) {
                    ew.eq("email", entry.getValue().toString());
                }
                if (entry.getKey().equals("gender")) {
                    ew.like("gender", entry.getValue().toString());
                }
            }
        }
        return ew;
    }

    @Override
    public List<UserRole> listUserRole(Integer userId) {
        EntityWrapper<UserRole> ew = new EntityWrapper<>();
        ew.eq("user_id",userId);
        return userRoleMapper.selectList(ew);
    }


    @Transactional
    private void authorize(Integer userId,List<Integer> assignRoleIds,List<Integer> dbRoleIds)
            throws Exception{
        //循环删除数据库有，但指派权限中不包含的权限
        for(Integer roleId : dbRoleIds){
            if(!contain(roleId,assignRoleIds)){
                EntityWrapper<UserRole> ew = new EntityWrapper<>();
                ew.eq("user_id",userId).eq("role_id",roleId);
                userRoleMapper.delete(ew);
            }
        }

        //循环增加指派权限中有，但数据库中不包含的权限
        for (Integer roleId : assignRoleIds){
            if(!contain(roleId,dbRoleIds)){
                UserRole userRole = new UserRole();
                userRole.setUserId(userId);
                userRole.setRoleId(roleId);
                userRoleMapper.insert(userRole);
            }
        }
    }

    @Override
    public List<UserBo> listUsers() {
        EntityWrapper<UserBo> ew = new EntityWrapper<>();
        return userMapper.listUsers(ew);
    }

    private boolean contain(Integer aim, List<Integer> collection) {
        for (Integer i : collection) {
            if (aim.equals(i)) return true;
        }
        return false;
    }
}
